package com.liyuci.core.helper;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * ip地址工具类
 * @author liyuci
 * @date 2018-02-04 16:44:04
 */

public class IPAddressHelper {

	public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        ip = getIPAddr(ip);
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        ip = getIPAddr(ip);
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        ip = getIPAddr(ip);
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        ip = getIPAddr(ip);
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        } if("0:0:0:0:0:0:0:1".endsWith(ip)){
        	ip = "127.0.0.1";
        } else {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        }        
        return ip;
    }

    /**
     * @param ip IP地址
     * @return 获取IP地址, 切分IP地址格式, 并屏蔽内网IP
     */
    private static String getIPAddr(String ip) {
        if (StringUtils.isBlank(ip)) {
            return null;
        }
        String[] ips = ip.split(",");
        for (String sIp : ips) {
            if (sIp.startsWith("10.") || sIp.startsWith("192.168.") || sIp.startsWith("172.16.") ||
                    sIp.startsWith("172.17.") || sIp.startsWith("172.18.") || sIp.startsWith("172.19.") ||
                    sIp.startsWith("172.20.") || sIp.startsWith("172.21.") || sIp.startsWith("172.22.") ||
                    sIp.startsWith("172.23.") || sIp.startsWith("172.24.") || sIp.startsWith("172.25.") ||
                    sIp.startsWith("172.26.") || sIp.startsWith("172.27.") || sIp.startsWith("172.28.") ||
                    sIp.startsWith("172.29.") || sIp.startsWith("172.30.") || sIp.startsWith("172.31.")) {
                continue;
            }
            return sIp;
        }
        return null;
    }
}
